package com.scott.wechat.service;

import java.util.Arrays;
import java.util.stream.Stream;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


@Service
public class WechatService {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(WechatService.class);
	
	@Value("${wechat.token}")
	private String token;
	
	@Value("${wechat.appid}")
	private String appId;
	
	@Value("${wechat.secret}")
	private String secret;
	
	public boolean checkSignature(String signature, String timestamp, String nonce, String echostr) {
		LOGGER.debug("进入验证access");  
        String[] params = new String[] {token, timestamp, nonce};
        
        // 将token,timestamp,nonce三个参数进行字典排序
        Arrays.sort(params);
        
        // 将数组中的元素依次相加 array[0] + array[1] + array[2]
        String srcKey = Stream.of(params).reduce("",(x,y)-> x+y);
        
        // sha1加密
        String temp = DigestUtils.sha1Hex(srcKey);
        
        if(StringUtils.isNotBlank(temp) && StringUtils.equals(temp, signature)) {
        		LOGGER.debug("成功返回 echostr：" + echostr);
        		return true;
        }
        LOGGER.debug("失败 认证");  
        return false;  
	}
}
